package com.itheima.easyexceldemo.aspect;

import com.itheima.easyexceldemo.annotation.AutoAnnotation;
import com.itheima.easyexceldemo.mapper.LogMapper;
import com.itheima.easyexceldemo.pojo.OperationLog;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * 切面类
 *
 * @Author mr.luo
 * @Date 13 4月 2025 09:56
 */
@Component
@Slf4j
@Aspect
public class OperationLogAspect {
    @Autowired
    private LogMapper logMapper;

    @Pointcut("execution(* com.itheima.easyexceldemo.*.*.*(..))&& @annotation(com.itheima.easyexceldemo.annotation.AutoAnnotation)")
    public void pt() {
    }

    //    @Around("execution(* com.itheima.easyexceldemo.service.*(..))")
    @Around("pt()")  //环绕通知
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        log.info("环绕通知");
        long startTime = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        long endTime = System.currentTimeMillis();
        long costTime = endTime - startTime;

        //开始构建日志对象
        OperationLog operationLog = new OperationLog();

        operationLog.setOperateEmpId(1);

        operationLog.setOperateTime(LocalDateTime.now());

        // 获取目标方法所在类的类名
        String className = joinPoint.getTarget().getClass().getName();
        operationLog.setClassName(className);

        // 获取方法名
        String methodName = joinPoint.getSignature().getName();
        operationLog.setMethodName(methodName);

        // 获取方法参数
        Object[] args = joinPoint.getArgs();
        operationLog.setMethodParams(Arrays.toString(args));

        // 获取返回值
        if (result != null) {
            String resultString = result.toString();
            operationLog.setReturnValue(resultString);
        }else {
            operationLog.setReturnValue("null");
        }
        //设置耗时
        operationLog.setCostTime(costTime);
        //获取被拦截方法的注解的操作类型
//        MethodSignature signature = (MethodSignature) joinPoint.getSignature();//方法签名对象
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        AutoAnnotation annotation = signature.getMethod().getAnnotation(AutoAnnotation.class);
        operationLog.setOperationType(annotation.value().name());

        logMapper.insert(operationLog);
        //返回结果
        return result;

    }
}
